import * as SysUserAPI from '@/api/sysUser'
import {
    getSotrageToken,
    removeStorageToken,
    setStorageToken,
    setStorageUser,
    getStorageUser,
    removeStorageUser
} from '@/utils/storage'
import {resetRouter} from '@/router'

const getDefaultState = () => {
  return {
      token: getSotrageToken(),
      id: getStorageUser().id,
      name: getStorageUser().name,
      avatar: getStorageUser().avatar
  }
}

const state = getDefaultState()

const mutations = {
    resetState: (state) => {
        Object.assign(state, getDefaultState())
    },
    setToken: (state, token) => {
        state.token = token
    },
    setName: (state, name) => {
        state.name = name
    },
    setAvatar: (state, avatar) => {
        state.avatar = avatar
    },
    setId: (state, id) => {
        state.id = id
    }
}

const actions = {
  // 用户登录
  login({commit}, userInfo) {
      const {name, password} = userInfo
      return SysUserAPI.login({name: name.trim(), password: password}).then(result => {
          const {data} = result
          commit('setToken', data.token)
          setStorageToken(data.token)
          const {id, name, avatar} = data
          commit('setId', id)
          commit('setName', name)
          commit('setAvatar', avatar)
          setStorageUser({id, name, avatar})
      })
  },

  // 查询用户信息
  getInfo({commit, state}) {
      return SysUserAPI.getInfo().then(response => {
          const {data} = response
          if (!data) {
              return Promise.reject('查询用户信息失败, 请重新登录!')
          }
          // 返回数据中如果有用户角色和权限数据，则建议在本地存储
          // TODO
      })
  },

  // 登出
  logout({commit, state}) {
      return SysUserAPI.logout(state.token).then(() => {
          removeStorageToken(); //清除本地存储的token
          removeStorageUser(); //清除本地存储的user
          resetRouter(); //重置路由数据
          commit('resetState');//重置用户状态（token、name、avatar、id)
      })
  },

  //重置token
  resetToken({commit}) {
      removeStorageToken(); //清除本地存储的token
      commit('resetState');//重置用户状态（token、name、avatar、id)
      return Promise.resolve();//成功
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
